<?php

namespace App\Http\Controllers\Wechat;

use App\Events\OrderEvent;
use App\Http\Controllers\Controller;
use App\Http\Controllers\H5\CommissionController;
use App\Models\Trade;
use App\WeChat\Response\JsApiPayResponse;
use App\WeChat\Response\QueryOrderResponse;
use App\WeChat\WechatDefaultConfig;

class NotifyController extends Controller
{
    use WechatDefaultConfig;

    /**
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function index()
    {
        $xml = $this->request->getContent();
        $response = new JsApiPayResponse($this->xmlToArray($xml));

        //file_put_contents(storage_path('/notify.php'), json_encode($response->response()));

        if ($response->tradeSuccess()) {
            $queryRes = new QueryOrderResponse($this->payment()->order->queryByOutTradeNumber($response->outTradeNo()));
            if ($queryRes->tradeSuccess()) {
                $trade = Trade::where('out_trade_no', $response->outTradeNo())->first();
                if ($trade->trade_status == 1) {
                    $order = $trade->order;
                    $order->changeToPaid();

                    event(new OrderEvent($order, 'paid'));
                    
                    //订单支付成功后计算佣金
                     CommissionController::getuserparentcommis($response->outTradeNo());
                }
            }
        }
    }

    private function xmlToArray($xml){
        //将XML转为array
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $array = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $array;
    }
}
